package com.hmily.cloud.elasticsearch.mockito.elasticsearch_client;

import co.elastic.clients.ApiClient;
import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.io.Closeable;
import java.io.IOException;

import static com.hmily.cloud.elasticsearch.mockito.elasticsearch_client.ElasticsearchClientConsts.ES_HOST_NAME;
import static com.hmily.cloud.elasticsearch.mockito.elasticsearch_client.ElasticsearchClientConsts.ES_PORT;


/**
 * <h1>使用 ElasticsearchClient 链接 ES 服务端的客户端工具类。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2024/7/9 06:14
 */
public class ElasticsearchClientUtils {

    /**
     * <h2>创建ES客户端(阻塞创建)。</h2>
     *
     * @param:
     * @return: co.elastic.clients.elasticsearch.ElasticsearchClient
     */
    public static ElasticsearchClient createClient() {
        RestClient restClient = RestClient.builder(new HttpHost(ES_HOST_NAME, ES_PORT)).build();

        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        return new ElasticsearchClient(transport);
    }

    /**
     * <h2>创建ES客户端(非阻塞创建)。</h2>
     *
     * @param:
     * @return: co.elastic.clients.elasticsearch.ElasticsearchAsyncClient
     */
    public static ElasticsearchAsyncClient createAsyncClient() {
        RestClient restClient = RestClient.builder(new HttpHost(ES_HOST_NAME, ES_PORT)).build();

        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        return new ElasticsearchAsyncClient(transport);
    }

    /**
     * <h2>关闭流对象。</h2>
     *
     * @param: stream
     * @return: void
     */
    public static void closeStream(ApiClient client) {
        if (client == null) {
            return;
        }
        try {
            client._transport().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}